"use client"

import React, { useState, useEffect } from 'react'
import { MainLayout } from '@/components/layout/main-layout'
import { Button } from '@/components/ui/button'
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar'
import { 
  Plus, 
  Search, 
  Filter,
  Activity,
  Heart,
  Weight,
  Thermometer,
  TrendingUp,
  TrendingDown,
  Calendar
} from 'lucide-react'

// 健康记录数据类型
interface HealthRecord {
  id: number
  userId: number
  recordType: string
  value: any
  unit: string | null
  recordDate: string
  notes: string | null
  user: {
    id: number
    name: string | null
    email: string
  }
}

// 记录类型配置
const recordTypeConfig = {
  blood_pressure: {
    label: '血压',
    icon: Heart,
    color: 'red',
    unit: 'mmHg'
  },
  heart_rate: {
    label: '心率',
    icon: Activity,
    color: 'pink',
    unit: 'bpm'
  },
  weight: {
    label: '体重',
    icon: Weight,
    color: 'blue',
    unit: 'kg'
  },
  temperature: {
    label: '体温',
    icon: Thermometer,
    color: 'orange',
    unit: '°C'
  }
}

// 健康记录卡片组件
function HealthRecordCard({ record }: { record: HealthRecord }) {
  const config = recordTypeConfig[record.recordType as keyof typeof recordTypeConfig]
  const Icon = config?.icon || Activity
  
  let displayValue = record.value
  if (record.recordType === 'blood_pressure' && typeof record.value === 'object') {
    displayValue = `${record.value.systolic}/${record.value.diastolic}`
  }

  return (
    <div className="bg-white rounded-lg border border-gray-200 p-4 hover:border-blue-300 transition-colors">
      <div className="flex items-start justify-between">
        <div className="flex items-center space-x-3">
          <div className={`p-2 rounded-full bg-${config?.color || 'blue'}-100`}>
            <Icon className={`h-5 w-5 text-${config?.color || 'blue'}-600`} />
          </div>
          <div>
            <h3 className="font-medium text-gray-900">
              {config?.label || record.recordType}
            </h3>
            <p className="text-sm text-gray-500">
              {record.user.name || record.user.email}
            </p>
          </div>
        </div>
        <div className="text-right">
          <div className="text-lg font-semibold text-gray-900">
            {displayValue} {record.unit || config?.unit}
          </div>
          <div className="text-xs text-gray-500 flex items-center">
            <Calendar className="h-3 w-3 mr-1" />
            {new Date(record.recordDate).toLocaleDateString('zh-CN')}
          </div>
        </div>
      </div>
      
      {record.notes && (
        <div className="mt-3 pt-3 border-t border-gray-100">
          <p className="text-sm text-gray-600">{record.notes}</p>
        </div>
      )}
    </div>
  )
}

export default function HealthPage() {
  const [records, setRecords] = useState<HealthRecord[]>([])
  const [loading, setLoading] = useState(true)
  const [searchTerm, setSearchTerm] = useState('')
  const [selectedType, setSelectedType] = useState<string>('all')

  // 模拟健康记录数据
  useEffect(() => {
    const mockRecords: HealthRecord[] = [
      {
        id: 1,
        userId: 1,
        recordType: 'blood_pressure',
        value: { systolic: 120, diastolic: 80 },
        unit: 'mmHg',
        recordDate: '2024-01-15T08:00:00Z',
        notes: '早晨测量，状态良好',
        user: { id: 1, name: '张三', email: 'zhangsan@example.com' }
      },
      {
        id: 2,
        userId: 2,
        recordType: 'heart_rate',
        value: 72,
        unit: 'bpm',
        recordDate: '2024-01-15T09:30:00Z',
        notes: '运动后测量',
        user: { id: 2, name: '李四', email: 'lisi@example.com' }
      },
      {
        id: 3,
        userId: 1,
        recordType: 'weight',
        value: 68.5,
        unit: 'kg',
        recordDate: '2024-01-14T07:00:00Z',
        notes: null,
        user: { id: 1, name: '张三', email: 'zhangsan@example.com' }
      },
      {
        id: 4,
        userId: 3,
        recordType: 'temperature',
        value: 36.5,
        unit: '°C',
        recordDate: '2024-01-14T18:00:00Z',
        notes: '体温正常',
        user: { id: 3, name: '王五', email: 'wangwu@example.com' }
      }
    ]
    
    setTimeout(() => {
      setRecords(mockRecords)
      setLoading(false)
    }, 1000)
  }, [])

  const filteredRecords = records.filter(record => {
    const matchesSearch = 
      record.user.name?.toLowerCase().includes(searchTerm.toLowerCase()) ||
      record.user.email.toLowerCase().includes(searchTerm.toLowerCase()) ||
      recordTypeConfig[record.recordType as keyof typeof recordTypeConfig]?.label.includes(searchTerm)
    
    const matchesType = selectedType === 'all' || record.recordType === selectedType
    
    return matchesSearch && matchesType
  })

  const stats = {
    total: records.length,
    bloodPressure: records.filter(r => r.recordType === 'blood_pressure').length,
    heartRate: records.filter(r => r.recordType === 'heart_rate').length,
    weight: records.filter(r => r.recordType === 'weight').length,
    temperature: records.filter(r => r.recordType === 'temperature').length
  }

  return (
    <MainLayout title="健康数据">
      <div className="space-y-6">
        {/* 操作栏 */}
        <div className="flex items-center justify-between">
          <div className="flex items-center space-x-4">
            <div className="relative">
              <Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-gray-400" />
              <input
                type="text"
                placeholder="搜索健康记录..."
                value={searchTerm}
                onChange={(e) => setSearchTerm(e.target.value)}
                className="h-10 w-64 rounded-md border border-gray-300 bg-white pl-10 pr-4 text-sm placeholder:text-gray-400 focus:border-blue-500 focus:outline-none focus:ring-1 focus:ring-blue-500"
              />
            </div>
            <select
              value={selectedType}
              onChange={(e) => setSelectedType(e.target.value)}
              className="h-10 rounded-md border border-gray-300 bg-white px-3 text-sm focus:border-blue-500 focus:outline-none focus:ring-1 focus:ring-blue-500"
            >
              <option value="all">所有类型</option>
              <option value="blood_pressure">血压</option>
              <option value="heart_rate">心率</option>
              <option value="weight">体重</option>
              <option value="temperature">体温</option>
            </select>
          </div>
          <Button>
            <Plus className="h-4 w-4 mr-2" />
            添加记录
          </Button>
        </div>

        {/* 统计信息 */}
        <div className="grid grid-cols-1 md:grid-cols-5 gap-4">
          <div className="bg-white rounded-lg border border-gray-200 p-4">
            <div className="text-2xl font-bold text-gray-900">{stats.total}</div>
            <div className="text-sm text-gray-500">总记录数</div>
          </div>
          <div className="bg-white rounded-lg border border-gray-200 p-4">
            <div className="text-2xl font-bold text-red-600">{stats.bloodPressure}</div>
            <div className="text-sm text-gray-500">血压记录</div>
          </div>
          <div className="bg-white rounded-lg border border-gray-200 p-4">
            <div className="text-2xl font-bold text-pink-600">{stats.heartRate}</div>
            <div className="text-sm text-gray-500">心率记录</div>
          </div>
          <div className="bg-white rounded-lg border border-gray-200 p-4">
            <div className="text-2xl font-bold text-blue-600">{stats.weight}</div>
            <div className="text-sm text-gray-500">体重记录</div>
          </div>
          <div className="bg-white rounded-lg border border-gray-200 p-4">
            <div className="text-2xl font-bold text-orange-600">{stats.temperature}</div>
            <div className="text-sm text-gray-500">体温记录</div>
          </div>
        </div>

        {/* 健康记录列表 */}
        <div className="bg-white rounded-lg border border-gray-200">
          <div className="p-6 border-b border-gray-200">
            <h2 className="text-lg font-semibold text-gray-900">
              健康记录 ({filteredRecords.length})
            </h2>
          </div>
          
          {loading ? (
            <div className="p-8 text-center">
              <div className="h-8 w-8 animate-spin rounded-full border-4 border-blue-600 border-t-transparent mx-auto mb-4"></div>
              <p className="text-gray-500">加载中...</p>
            </div>
          ) : (
            <div className="p-6">
              {filteredRecords.length === 0 ? (
                <div className="text-center py-8">
                  <Activity className="h-12 w-12 text-gray-400 mx-auto mb-4" />
                  <p className="text-gray-500">没有找到匹配的健康记录</p>
                </div>
              ) : (
                <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                  {filteredRecords.map((record) => (
                    <HealthRecordCard key={record.id} record={record} />
                  ))}
                </div>
              )}
            </div>
          )}
        </div>
      </div>
    </MainLayout>
  )
}